/*
 * Copyright (C) 2006 Holger Hees
 *
 * Licensed under the terms of the GNU Lesser General Public License:
 *      http://www.opensource.org/licenses/lgpl-license.php
 *
 * File Author:
 *      Holger Hees (hhees at systemconcept.de)
 *      omonymos at users.sourceforge.net
 *
 */


// Command Object
var FCKDynamicCSSCommand = function(name) {
    this.Name = name ; 
}
FCKDynamicCSSCommand.prototype.GetState = function() {
    return;
}
FCKDynamicCSSCommand.prototype.Execute = function(itemText, itemLabel) {
    if(dynamicCSSSelection){
        dynamicCSSCombo.DeselectAll();
        dynamicCSSCombo.SelectItem(itemText);
        dynamicCSSSelection.className=itemText;

		var formatedName=itemLabel.childNodes[0].innerHTML;
        dynamicCSSCombo.SetLabel( formatedName );
    }
}
FCKCommands.RegisterCommand( 'dynamicCSSCommand' , new FCKDynamicCSSCommand('dynamicCSS') ) ; 



// Combobox Object
var FCKDynamicCSSToolbar=function(tooltip,style){
    this.Command=FCKCommands.GetCommand('dynamicCSSCommand');
	this.CommandName='dynamicCSSCommand';
    this.Tooltip=tooltip?tooltip:this.Label;
    this.Style=style;
    this.FieldWidth=100;
    this.PanelWidth=150;
};
FCKDynamicCSSToolbar.prototype=new FCKToolbarSpecialCombo;
FCKDynamicCSSToolbar.prototype.GetLabel=function(){
    return "CSS";
};

var dynamicCSSStyleNames=new Array();
var dynamicCSSStyleCheck=new Array();

var dynamicCSSRules=false;
var dynamicCssRulesLength=0;
var dynamicCSSCombo=false;
var dynamicCSSSelection=false;
FCKDynamicCSSToolbar.prototype.CreateItems=function(A){
    dynamicCSSCombo=this._Combo;

	var oTargetDoc = dynamicCSSCombo._Panel.Document ;
	// Add the Editor Area CSS to the Styles panel so the style classes are previewed correctly.
	var aCSSs = FCKConfig.EditorAreaCSS ;
	for ( var i = 0 ; i < aCSSs.length ; i++ ){
		FCKTools.AppendStyleSheet( oTargetDoc, aCSSs[i] ) ;
	}
	// For some reason Gecko is blocking inside the "RefreshVisibleItems" function.
	if ( ! FCKBrowserInfo.IsGecko )
		oTargetDoc.OnBeforeClick = this.RefreshVisibleItems ;
}
FCKToolbarItems.RegisterItem( 'dynamicCSS'	, new FCKDynamicCSSToolbar( 'CSS', FCK_TOOLBARITEM_ICONTEXT ) ) ;







// Common Functions
FCKDynamicCSSToolbar._StatusListener = function(editorInstance){
    if(FCK_STATUS_COMPLETE && dynamicCssRulesLength==0 && dynamicCSSCombo){
        FCKDynamicCSSToolbar.initCSS(editorInstance.Name,0,5);
        FCKDynamicCSSToolbar._SelectionListener(editorInstance);
    }
}
FCK.Events.AttachEvent('OnStatusChange',FCKDynamicCSSToolbar._StatusListener);


var formatTag=new Array();
formatTag['H1']=true;
formatTag['H2']=true;
formatTag['H3']=true;
formatTag['H4']=true;
formatTag['H5']=true;
formatTag['H6']=true;
formatTag['P']=true;
formatTag['SPAN']=true;
formatTag['DIV']=true;
formatTag['FONT']=true;


FCKDynamicCSSToolbar._SelectionListener = function(editorInstance){
    var element = editorInstance.Selection.GetParentElement();

    if(element && dynamicCSSCombo){
        dynamicCSSSelection=element;

        dynamicCSSCombo.Items=new Array();
        dynamicCSSCombo._ItemsHolderEl.innerHTML='';

        dynamicCSSCombo.SelectItem('');
        if(dynamicCSSStyleCheck[element.tagName] && dynamicCSSStyleCheck[element.tagName]['none']){
            if(formatTag[element.tagName]){ 
				dynamicCSSCombo.AddItem('','<'+element.tagName+'>&lt;Normal&gt;</'+element.tagName+'>');
			}
			else{
				dynamicCSSCombo.AddItem('', '<span>&lt;Normal&gt;</span>');
            }
			dynamicCSSCombo.SetLabel( '<span>&lt;Normal&gt;</span>' );
        }
        else{
            dynamicCSSCombo.AddItem('', '<span>Normal</span>');
            dynamicCSSCombo.SetLabel( '<span>Normal</span>' );
        }

        // einzelnen Tagarten durchlaufen
        for(var tag in dynamicCSSStyleNames){
            if((tag=='all') || tag==element.tagName){
                for(var cssClass in dynamicCSSStyleNames[tag]){
                    if(typeof dynamicCSSStyleNames[tag][cssClass]=='string'){
                        if(dynamicCSSStyleNames[tag][cssClass]!='none'){
                            cssName=dynamicCSSStyleNames[tag][cssClass];
							if(tag!='all') cssName='&lt;'+cssName+'&gt;';

							if(formatTag[tag]){ 
								dynamicCSSCombo.AddItem(dynamicCSSStyleNames[tag][cssClass],'<'+tag+' class=\"' + dynamicCSSStyleNames[tag][cssClass] + '\">' + cssName + '</'+tag+'>');
							}
							else if(tag=='all'){ 
								dynamicCSSCombo.AddItem(dynamicCSSStyleNames[tag][cssClass],'<span class=\"' + dynamicCSSStyleNames[tag][cssClass] + '\">' + cssName + '</span>');
							}
							else{
								dynamicCSSCombo.AddItem(dynamicCSSStyleNames[tag][cssClass],'<span>'+cssName+'</span>');
							}

                            if(element.className==dynamicCSSStyleNames[tag][cssClass]){
								//dynamicCSSSelectionName=cssName
                                dynamicCSSCombo.SelectItem(dynamicCSSStyleNames[tag][cssClass]);
                                dynamicCSSCombo.SetLabel( cssName );
                            }
                        }
                    }
                }
            }
        }
    }
    else{
        dynamicCSSSelection=false;
    }
}
FCK.Events.AttachEvent('OnSelectionChange',FCKDynamicCSSToolbar._SelectionListener);





















// init
FCKDynamicCSSToolbar.initCSS=function(editorInstanceName,parseCount,parseMaxCount){
    FCKDynamicCSSToolbar.parseStyleSheet(editorInstanceName);
    if(dynamicCssRulesLength<dynamicCSSRules.length){
        //alert(dynamicCssRulesLength+' '+dynamicCSSRules.length);
        dynamicCssRulesLength=dynamicCSSRules.length;
        FCKDynamicCSSToolbar.applyCSSElements();
        for(var tag in dynamicCSSStyleNames){
            if(dynamicCSSStyleNames[tag].sort){
                dynamicCSSStyleNames[tag].sort();
            }
        }
    }
    if(parseCount<parseMaxCount){
        parseCount+=1;
        window.setTimeout("FCKDynamicCSSToolbar.initCSS('"+editorInstanceName+"',"+parseCount+","+parseMaxCount+")",parseCount*1000);
    }
}

// parsing
FCKDynamicCSSToolbar.parseStyleSheet=function(editorInstanceName){

    iframe = FCKeditorAPI.GetInstance(editorInstanceName).EditorDocument;

    dynamicCSSRules=new Array();

    for(i=0;i<iframe.styleSheets.length;i++){
        if(FCKBrowserInfo.IsIE){
            try{
                if(iframe.styleSheets[i].rules){
                    FCKDynamicCSSToolbar.applyCSSRule(iframe.styleSheets[i].rules);
                }
                // @import StyleSheets (IE)
                if(iframe.styleSheets[i].imports){
                    for(j=0;j<iframe.styleSheets[i].imports.length;j++){
                        FCKDynamicCSSToolbar.applyCSSRule(iframe.styleSheets[i].imports[j].rules);
                    }
                }
            }
            catch(e){
                //alert(e);
            }
        }
        else {
            try{
                FCKDynamicCSSToolbar.applyCSSRule(iframe.styleSheets[i].cssRules);
            }
            catch(e){
                //alert(e);
            }
        }
    }
}

FCKDynamicCSSToolbar.applyCSSRule=function(cssRules){
    for(rule in cssRules){
        // StyleRule
        if(cssRules[rule].selectorText){
            dynamicCSSRules.push(cssRules[rule]);
        }
        // ImportRule (Mozilla)
        else if(cssRules[rule].styleSheet){
            FCKDynamicCSSToolbar.applyCSSRule(cssRules[rule].styleSheet.cssRules);
        }
    }
}

FCKDynamicCSSToolbar.applyCSSElements=function(){
    for(i=0;i<dynamicCSSRules.length;i++){
        // split equal Styles (Mozilla-specific) e.q. head, body {border:0px}
        // for ie not relevant. returns allways one element
        cssElements = dynamicCSSRules[i].selectorText.split(",");

        for(k=0;k<cssElements.length;k++){
            cssElement=cssElements[k];
            // keine Hover Pseudoformate auswerten
            if(cssElement.search(/:+/)==-1 && cssElement.search(/\[+/)==-1 && cssElement.search(/FCK__+/)==-1){
                spacePos=cssElement.indexOf(' ');
                if(spacePos==0){
                    cssElement=cssElement.trim();
                    spacePos=cssElement.indexOf(' ');
                }
                if(spacePos>-1){
                    // nur den Tagnamen mit eventueller Klasse holen
                    cssElement=cssElement.substr(0,cssElement.indexOf(' '));
                }
                cssElement = cssElement.split(".");

                tagName=cssElement[0].toUpperCase().trim();
                className=cssElement[1];

                if(!tagName) tagName='all';
                if(!className) className='none';

                if(!dynamicCSSStyleCheck[tagName]){
                    dynamicCSSStyleCheck[tagName]=new Array();
                    dynamicCSSStyleNames[tagName]=new Array();
                }
                if(!dynamicCSSStyleCheck[tagName][className]){
                    dynamicCSSStyleCheck[tagName][className]=true;
                    dynamicCSSStyleNames[tagName].push(className);
                }
            }
        }
    }
}
